import { clearToken, getAccessToken } from "./auth";

export const baseUrl = 'http://192.168.0.196:2022'

// 全局请求封装
const useRequest = (method, url, data = {}, header = {}) => {
  const accessToken = getAccessToken()
  if(accessToken && !header.Authorization) {
    header.Authorization = `Bearer ${accessToken}`
  }
  return new Promise((resolve, reject) => {
    uni.request({
      url: baseUrl + url,
      method,
      data,
      header,
      success: (res) => {
        if(res.statusCode === 200) {
          resolve(res.data)
        } else {
          if (res.statusCode === 401) {
            clearToken()
            if (res?.data?.code === 40101) {
              uni.reLaunch({
                url: '/pages/mine/mine'
              })
            }
          }
          reject(res.data)
          if (res?.data?.message) {
            uni.showToast({
              icon:"none",
              title:res?.data?.message
            })
          }
        }
      },
      fail(err) {
        reject(err);
      }
    })
  })
}

// POST 请求
export const usePost = (url, data = {}, {
  header = {}
} = { params: {}, header: {} }) => {
  return useRequest('POST', url, data, header)
}

// PUT 请求
export const usePut = (url, data = {}, {
  header = {}
} = { params: {}, header: {} }) => {
  return useRequest('PUT', url, data, header)
}

// DELETE 请求
export const useDelete = (url, {
  params = {},
  header = {}
} = { params: {}, header: {} }) => {
  return useRequest('DELETE', url, params, header)
}

// GET 请求
export const useGet = (url, {
  params = {},
  header = {}
} = { params: {}, header: {} }) => {
  return useRequest('GET', url, params, header)
}

export const useUpload = (url, filePath) => {
  const accessToken = getAccessToken()
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: baseUrl + url,
      header: {
        Authorization: `Bearer ${accessToken}`
      },
      name: 'file',
      filePath,
      async success(ret) {
        if (ret.statusCode === 200) {
          resolve(JSON.parse(ret.data))
        } else {
          if (ret.statusCode === 401) {
            clearToken()
            uni.reLaunch({
              url: '/pages/mine/mine'
            })
            console.log(ret?.data?.message)
            uni.showToast({
              icon:"none",
              title:JSON.parse(ret.data).message
            })
          }
          reject(ret)
        }
      },
      fail(err) {
        reject(err)
      }
    })
  })
}
